// 引入 router
import { createRouter, createWebHistory } from 'vue-router'
// @ts-ignore
import Cookies from "js-cookie";
import {isEmpty} from "../utils/utils";

const routes = [
  {
    path: '/',
    redirect: '/salesPromotion',
  },
  {
    path: '/salesPromotion',
    name: 'salesPromotion',
    title: 'salesPromotion',
    redirect: '/salesPromotion/loginBefore',
    component: () => import('../views/salesPromotion/index.vue'), //.vue不能省略
    children:[
      {
        path: '/salesPromotion/loginBefore',
        name: 'loginBefore',
        title: 'loginBefore',
        component: () => import('../views/salesPromotion/children/login/loginBefore.vue'), //.vue不能省略
      },
      {
        path: '/salesPromotion/login',
        name: 'login',
        title: 'login',
        component: () => import('../views/salesPromotion/children/login/index.vue'), //.vue不能省略
      },
      {
        path: '/salesPromotion/user',
        name: 'user',
        title: 'user',
        component: () => import('../views/salesPromotion/children/user/index.vue'), //.vue不能省略
      }
    ]
  },
]
// 配置router对象
const router = createRouter({
  // history: createWebHistory("/inewsSales/"),
  history: createWebHistory("/"),
  routes
})

/**
 * 获取url上query
 */
const getQuery = () => {
  let query: any = {}
  const url = window.location.href
  if (url.indexOf('?') !== -1) {
    let queryArr: Array<string> = []
    const urlQuery: string = url.split('?')[1]
    if (urlQuery.indexOf('&') !== -1) {
      queryArr = urlQuery.split('&')
    } else {
      queryArr = [urlQuery]
    }
    for (let i: number = 0; i < queryArr.length; i++) {
      if (queryArr[i].indexOf('=') !== -1) {
        const key: any = queryArr[i].split('=')[0]
        const value: any = queryArr[i].split('=')[1]
        query[key] = value
      }
    }
  }
  return query
}


const urlQuery:any = getQuery()


// 全局导航守卫
router.beforeEach((to, from,next) => {
  if(Cookies.get('refreshToken') || to.path.indexOf('/login') !== -1){
    // 是否登录或进入页面是登录页
    console.log('urlQuery',urlQuery)
    if(to.path.indexOf('/loginBefore')){
      next()
    }else if(isEmpty(urlQuery.code)){
      next('/salesPromotion')
    }
  }else{
    next('/salesPromotion')
  }
})
export default router

